#include <stdio.h>
#include <stdlib.h>
#include "common.h"

Reader* ReaderCreate(uint32 iLength)
{
	//Allocate memory for the reader structure.
	Reader* pReader = (Reader*)malloc(sizeof(pReader));

	//Create buffer and initialize it.
	pReader->buffer = (char*)malloc(iLength);
	pReader->current = pReader->buffer;
	pReader->bufferEnd = pReader->buffer + iLength;

	//Initialize file position.
	pReader->line = 0;
	pReader->column = 0;

	return pReader;
}

Reader* ReaderCreateFromFile(const char* sFilePath)
{
	int32 iRead = 0;
	int32 iLength = 0;
	FILE* pFile = null;
	Reader* pReader = null;

	//Try to open file.
	pFile = fopen(sFilePath, "rb");
	if (pFile != null)
	{
		//Get file content length.
		fseek((FILE*)pFile, 0, SEEK_END);
		iLength = ftell((FILE*)pFile);
		fseek((FILE*)pFile, 0, SEEK_SET);

		//Create file and set path.
		pReader = ReaderCreate(iLength);

		//Copy file content into the buffer.
		do
		{
			iRead += fread((pReader->buffer + iRead), 1, iLength-iRead, pFile);
		}while (iRead < iLength);

		//Close the file before finishing.
		fclose(pFile);
	}

	return pReader;
}

void ReaderFree(Reader* pReader)
{
	//If there is buffer allocated then free it.
	if (pReader->buffer != null) free(pReader->buffer);

	//Free the reader structure from memory
	free(pReader);
}


int32 ReaderRead(Reader* pReader)
{
	//Assume end of file.
	int32 cChar = EOF;

	//If we have not reached end of the buffer then read next character.
	if (pReader->current < pReader->bufferEnd)
	{
		//Read the next character and increment the current pointer.
		cChar = *(pReader->current++);

		//If the character is a new line then move the next line and reset the column to 0
		if (cChar == '\n')
		{
			pReader->line++;
			pReader->column= 0;
		}
		//Otherwise we are still on the same line then only increment the column number.
		else pReader->column++;
	}

	return cChar;
}

void ReaderSkip(Reader* pReader, uint32 iSkip)
{
	//Skip the specified number of character or until reaching end of file.
	while (iSkip-- > 0 && ReaderRead(pReader) != EOF);
}

int32 ReaderSkipUntilChar(Reader* pReader, int32 iChar)
{
	int32 iValue = ReaderPeek(pReader);
	while (iValue != EOF && iValue != iChar)
	{
		ReaderRead(pReader);
		iValue = ReaderPeek(pReader);
	}

	return iValue;
}

int32 ReaderReadUntilChar(Reader* pReader, String* sBuffer, int32 iChar)
{
	return 0;
}

int32 ReaderReadUntilString(Reader* pReader, String* sBuffer, wchar *sToken)
{
	int32 iChar = ReaderPeek(pReader);

	return iChar;
}






